﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Diagnostics;

namespace Security.Encryption
{
    public class X509CertificatesCreator
    {
        /// <summary>
        /// Creates a X509Certificate2 certificate with the specifired user name
        /// The tool makecert.exe contained in visual studio 8 is used to create the certificate
        /// </summary>
        /// <param name="userName">Username used in the certificate</param>
        /// <returns>X509Certificate2 certificsate</returns>
        public static X509Certificate2 Create(string userName)
        {
            // makecert -r -pe -n "CN=TestUser" -ss my -sr currentuser 
            //      -sky exchange .\TestUser.cer

            const string MakeCert =
                "C:\\Program Files\\Microsoft Visual Studio 8\\" +
                "Common7\\Tools\\Bin\\makecert.exe";

            string fileName = Path.ChangeExtension(Path.GetTempFileName(), "cer");
           // string userName = Guid.NewGuid().ToString();

            string arguments =
                string.Format("-r -pe -n \"CN={0}\" -ss my -a sha1 -sr currentuser -sky exchange \"{1}\"",
                userName, fileName);

            Process p = Process.Start(MakeCert, arguments);
            p.WaitForExit();

            byte[] certBytes = ReadFile(fileName);
            File.Delete(fileName);
            X509Certificate2 cert = new X509Certificate2(certBytes);
            return cert;

        }
        internal static byte[] ReadFile(string fileName)
        {
            using (FileStream f = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                int size = (int)f.Length;
                byte[] data = new byte[size];
                size = f.Read(data, 0, size);
                return data;
            }
        }
    }
}
